package la.bbs558.service.impl;

import cn.hutool.captcha.LineCaptcha;
import cn.hutool.core.util.NumberUtil;
import la.bbs558.entity.enums.CaptchaTypeEnum;
import la.bbs558.entity.enums.RedisKey;
import la.bbs558.entity.enums.ServerTypeEnum;
import la.bbs558.exception.MsgException;
import la.bbs558.service.VerifyCodeService;
import la.bbs558.strategy.send.SendContext;
import la.bbs558.util.Objs;
import la.bbs558.util.ValidUtils;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Objects;
import java.util.concurrent.TimeUnit;

@Service
@Slf4j
@RequiredArgsConstructor
public class VerifyCodeServiceImpl implements VerifyCodeService {


    private final RedisTemplate<String, Object> redisTemplate;

    @Override
    public LineCaptcha createSignInCode(String username) {
        SendContext sendContext = new SendContext();
        sendContext.setTo(username);
        sendContext.setTime(1);
        sendContext.setTimeUnit(TimeUnit.MINUTES);
        sendContext.setServerTypeEnum(ServerTypeEnum.LOGIN);
        sendContext.setCaptchaTypeEnum(CaptchaTypeEnum.GRAPH);
        sendContext.handle();
        return (LineCaptcha) sendContext.getResult();
    }

    @Override
    public void verifyCode(RedisKey redisKey, String username, String code) {
        Object rdsCode = redisTemplate.opsForValue().get(redisKey.spaceName(username));
        if (!Objects.equals(rdsCode, code)) {
            throw new MsgException("验证码错误");
        }
    }

    @Override
    public void removeCode(RedisKey redisKey,String key) {
        Boolean delete = redisTemplate.delete(redisKey.spaceName(key));
        Objs.isTrue(Boolean.TRUE.equals(delete), "验证码已失效");
    }

    @Override
    public void sendSignUpCode(String emailOrTel) {
        SendContext sendContext = new SendContext();
        sendContext.setTo(emailOrTel);
        sendContext.setTime(5);
        sendContext.setTimeUnit(TimeUnit.MINUTES);
        sendContext.setServerTypeEnum(ServerTypeEnum.REGISTER);
        boolean number = NumberUtil.isNumber(emailOrTel);
        boolean email = !number && ValidUtils.isEmail(emailOrTel);
        if(!number && !email){
            throw new MsgException("邮箱或手机号格式不正确");
        }
        sendContext.setCaptchaTypeEnum(number ? CaptchaTypeEnum.MESSAGE : CaptchaTypeEnum.MAIL);
        sendContext.handle();
    }


    @Override
    public void sendForGetCode(String emailOrTel) {
        SendContext sendContext = new SendContext();
        sendContext.setTo(emailOrTel);
        sendContext.setTime(5);
        sendContext.setTimeUnit(TimeUnit.MINUTES);
        sendContext.setServerTypeEnum(ServerTypeEnum.FORGET);
        sendContext.setCaptchaTypeEnum(NumberUtil.isNumber(emailOrTel) ? CaptchaTypeEnum.MESSAGE : CaptchaTypeEnum.MAIL);
        sendContext.handle();
    }

}
